<template>
  <div class="setting-page p-d">
    <el-row class="m-b b-f search-content border-radius-8 p-d">
      <div class="form-box">
        <SearchComp :searchForm="searchForm"
          :searchData="searchData"
          :searchAction="searchHandle"
          :search-form-select-tree="searchFormSelectTree">
          <template v-slot:departmentName="{ item }">
            <el-select :ref="`selectBox${item.prop}`"
              v-model="searchData.departmentName"
              filterable
              :placeholder="item.placeholder"
              :clearable="item.clearable ? item.clearable : false"
              @clear="clearSelect">
              <el-option class="select-tree"
                :value="dataOrgTree">
                <div class="select-tree-box">
                  <el-scrollbar style="height: 100%">
                    <el-tree ref="tree"
                      class="orgTree elc-tree"
                      :data="dataOrgTree"
                      default-expand-all
                      node-key="id"
                      :expand-on-click-node="false"
                      highlight-current
                      :props="defaultProps"
                      @node-click="(data) => changeTree(data, item.prop)" />
                  </el-scrollbar>
                </div>
              </el-option>
            </el-select>
          </template>
        </SearchComp>
      </div>
    </el-row>
    <el-tabs type="border-card">
      <el-tab-pane label="管理平台用户账号">
        <div class="">
          <el-row type="flex"
            class="m-b"
            justify="space-between">
            <div>
              <el-button type="primary"
                @click="addUser">新建用户</el-button>
            </div>
            <div>
              <el-button type="primary"
                @click="addUserBatch">批量导入用户</el-button>
              <el-button type="danger"
                @click="delUserBatch">批量删除用户</el-button>
            </div>
          </el-row>
          <TableCompEle ref="multipleTable"
            v-loading="loading"
            :tableData="tableData"
            :tableAction="tableAction"
            :isSelect="true"
            :isPageIndex="false"
            :isShowPage="true"
            :tableConfig="tableConfig"
            :queryParams="queryParams"
            @getPagination="getPagination"
            @handleSelectionChange="handleSelectionChange" />
        </div>
      </el-tab-pane>
      <el-tab-pane label="共享前台用户账号">
        <div class="">
          <TableCompEle ref="multipleTable"
            v-loading="loading"
            :tableData="tableData"
            :tableAction="tableAction2"
            :isSelect="true"
            :isPageIndex="false"
            :isShowPage="true"
            :tableConfig="tableConfig"
            :queryParams="queryParams"
            @getPagination="getPagination"
            @handleSelectionChange="handleSelectionChange" />
        </div>
      </el-tab-pane>
    </el-tabs>
    <UserDialog ref="userRef"
      :roles="roles"
      :data-org-tree="dataOrgTree"
      @init="initUser" />
    <BatchImport :add-form-visible="addFormVisible"
      @handleClose="handleClose"
      @listShow="listShow" />
  </div>
</template>

<script>
import BatchImport from './batchImport.vue'
import UserDialog from './userDialog.vue'
import {
  // selectPage,
  deleteUser,
  enableUser,
  userDetail
} from '@/api/user'
// import { roleSelect } from '@/api/systemRole'
// import { departmentTree } from '@/api/projectManage'
import userInfo from './userInfo.json'
export default {
  components: {
    UserDialog,
    BatchImport
  },
  data() {
    return {
      addFormVisible: false,
      dataOrgTree: [],
      tableData: [],
      tableConfig: [
        {
          prop: 'userName',
          label: '用户名称'
        },
        {
          prop: 'userRealName',
          label: '姓名'
        },
        {
          prop: 'userPhone',
          label: '联系方式'
        },
        {
          prop: 'roleName',
          label: '角色',
          width: 200
        },
        {
          prop: 'departmentName',
          label: '所属单位',
          width: 200
        },
        {
          prop: 'createTime',
          label: '创建时间'
        },
        {
          prop: 'enableFlag',
          label: '状态',
          isHandle: true,
          isType: 'Switch',
          isEdit: true,
          method: row => {
            this.changeStatus(row)
          }
        }
      ],
      tableAction: {
        width: () => '260px',
        fixed: 'right',
        operations: [
          {
            label: '修改',
            isLink: true,
            type: 'primary',
            method: row => {
              this.editUser(row)
            }
          },
          {
            label: '删除',
            isLink: true,
            type: 'danger',
            method: row => {
              this.dels(row)
            }
          },
          {
            label: '启用',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          },
          {
            label: '停用',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          },
          {
            label: '口令重置',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          }
        ]
      },
      tableAction2: {
        width: () => '200px',
        fixed: 'right',
        operations: [
          {
            label: '启用',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          },
          {
            label: '停用',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          },
          {
            label: '口令重置',
            isLink: true,
            type: 'primary',
            method: row => {
              this.dels(row)
            }
          }
        ]
      },
      defaultProps: {
        children: 'childrenDept',
        label: 'deptName'
      },
      searchFormSelectTree: [
        {
          type: 'Select',
          label: '部门名称:',
          clearable: true,
          prop: 'departmentName',
          placeholder: '请选择部门'
        }
      ],
      searchForm: {
        changeMethod: () => {
          this.queryParams.pageNum = 1
          this.paginationSize()
        },
        formData: [
          {
            type: 'Input',
            label: '用户名称:',
            prop: 'userName',
            clearable: true,
            placeholder: '请输入用户名称'
          },
          {
            type: 'Input',
            label: '姓名:',
            prop: 'userRealName',
            clearable: true,
            placeholder: '请输入姓名'
          },
          {
            type: 'Select',
            label: '状态:',
            prop: 'enableFlag',
            filterable: true,
            clearable: true,
            placeholder: '请选择状态',
            options: [
              { label: '开启', value: 'y' },
              { label: '关闭', value: 'n' }
            ],
            props: { label: 'label', value: 'value' }
          },
          {
            type: 'Select',
            label: '角色:',
            prop: 'roleId',
            filterable: true,
            clearable: true,
            placeholder: '请选择角色',
            options: [],
            sysKeys: { value: 'roleId', label: 'roleName' },
            change: () => this.paginationSize()
          }
        ]
      },
      searchHandle: [
        {
          label: '重置',
          handle: () => this.reset()
        }
      ],
      searchData: {
        departmentName: null,
        departmentId: null,
        usersName: null,
        enableFlag: null,
        roleId: null
      },
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      roles: [],
      multipleSelection: []
    }
  },
  created() {
    this.initTree()
    this.initUser()
    this.initRole()
  },
  methods: {
    getPagination() {
      this.initUser()
    },
    initRole() {
      let res = {
        code: 200,
        message: '操作成功',
        data: [
          {
            roleId: 1,
            roleName: '超级管理员',
            roleKey: 'superadmin',
            roleSort: 1,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '超级管理员',
            createTime: null,
            flag: false,
            superAdmin: true
          },
          {
            roleId: 2,
            roleName: '主管机关',
            roleKey: 'common',
            roleSort: 2,
            dataScope: '2',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '普通角色',
            createTime: null,
            flag: false,
            superAdmin: false
          },
          {
            roleId: 3,
            roleName: '大单位智能部门机关',
            roleKey: '1',
            roleSort: 3,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '1',
            createTime: null,
            flag: false,
            superAdmin: false
          },
          {
            roleId: 3,
            roleName: '管理单位管理员',
            roleKey: '1',
            roleSort: 3,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '1',
            createTime: null,
            flag: false,
            superAdmin: false
          },
          {
            roleId: 3,
            roleName: '设施仪器管理员',
            roleKey: '1',
            roleSort: 3,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '1',
            createTime: null,
            flag: false,
            superAdmin: false
          },
          {
            roleId: 3,
            roleName: '用户单位管理员',
            roleKey: '1',
            roleSort: 3,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '1',
            createTime: null,
            flag: false,
            superAdmin: false
          },
          {
            roleId: 3,
            roleName: '平台中心管理员',
            roleKey: '1',
            roleSort: 3,
            dataScope: '1',
            menuCheckStrictly: true,
            deptCheckStrictly: true,
            status: '0',
            remark: '1',
            createTime: null,
            flag: false,
            superAdmin: false
          }
        ]
      }
      // roleSelect().then((res) => {
      this.roles = res.data
      this.searchForm.formData[3].options = res.data
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    initUser() {
      // this.loading = true
      // const params = {
      //   currentPage: this.queryParams.pageNum,
      //   pageSize: this.queryParams.pageSize,
      //   queryString: {
      //     userName: this.searchData.userName ? this.searchData.userName : '',
      //     userRealName: this.searchData.userRealName ? this.searchData.userRealName : '',
      //     departmentId:
      //       this.searchData.departmentId !== null
      //         ? [this.searchData.departmentId]
      //         : [],
      //     enableFlag: this.searchData.enableFlag
      //       ? this.searchData.enableFlag
      //       : '',
      //     roleId: this.searchData.roleId ? [this.searchData.roleId] : []
      //   }
      // }
      // selectPage(params).then(res => {
      //   this.tableData = res.rows.map((item) => {
      //     item.enableFlag === 'y'
      //       ? (item.enableFlag = true)
      //       : (item.enableFlag = false)
      //     return item
      //   })
      let res = {
        code: 200,
        total: 5,
        rows: userInfo.rows
        // rows: [
        //   {
        //     userId: 1287,
        //     userName: 'wang',
        //     userRealName: '王滢熙',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-02 21:39:11',
        //     departmentName: '军事医学研究院',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 18702348729,
        //     enableFlag: 'y',
        //     roleName: '设施仪器管理员【助理】'
        //   },
        //   {
        //     userId: 1290,
        //     userName: 'gao',
        //     userRealName: '高兴盛',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '军事医学研究院',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 13387273947,
        //     enableFlag: 'y',
        //     roleName: '单位管理员【主任】'
        //   },
        //   {
        //     userId: 1280,
        //     userName: 'liu',
        //     userRealName: '刘洁',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 18093472839,
        //     enableFlag: 'y',
        //     roleName: '平台中心管理员【高工】'
        //   },
        //   {
        //     userId: 1270,
        //     userName: 'zhang',
        //     userRealName: '章婷玉',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '军事科技委',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 13938472617,
        //     enableFlag: 'y',
        //     roleName: '宏观管理部门【处长】'
        //   },
        //   {
        //     userId: 1270,
        //     userName: 'huang',
        //     userRealName: '黄丽丽',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '中国人民解放军总医院',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 15534928410,
        //     enableFlag: 'y',
        //     roleName: '普通用户【教授】'
        //   },
        //   {
        //     userId: 1270,
        //     userName: 'li',
        //     userRealName: '李彤彤',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '军事科学院',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 17928374610,
        //     enableFlag: 'y',
        //     roleName: '用户单位管理员'
        //   },
        //   {
        //     userId: 1270,
        //     userName: 'zhu',
        //     userRealName: '朱丹',
        //     userEmail: null,
        //     deptName: null,
        //     createBy: 'admin',
        //     createTime: '2024-01-16 15:10:09',
        //     departmentName: '军事科学院',
        //     departmentId: null,
        //     selectFlag: true,
        //     userHeadPath: null,
        //     userPhone: 13746283726,
        //     enableFlag: 'y',
        //     roleName: '平台中心管理员'
        //   }
        // ]
      }
      this.tableData = res.rows.map(item => {
        item.enableFlag === 'y'
          ? (item.enableFlag = true)
          : (item.enableFlag = false)
        return item
      })
      this.queryParams.total = res.total || 0
      // this.$refs.multipleTable.clearSelection();
      // }).catch(err => {
      //   console.log(err)
      // }).finally(() => {
      //   this.loading = false
      // })
    },
    initTree() {
      // departmentTree().then(res => {
      //   this.dataOrgTree = res.data
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    changeTree(data, prop) {
      this.searchData.departmentName = data.deptName
      this.searchData.departmentId = data.id
      this.$refs[`selectBox${prop}`].blur()
      this.paginationSize()
    },
    clearSelect() {
      this.searchData.departmentName = ''
      this.searchData.departmentId = ''
      this.paginationSize()
    },
    paginationSize() {
      this.queryParams.pageNum = 1
      this.initUser()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    reset() {
      this.searchData = {
        departmentName: null,
        departmentId: null,
        usersName: null,
        enableFlag: null,
        roleId: null
      }
      this.paginationSize()
    },
    addUser() {
      const obj = {
        title: '新建用户',
        data: {}
      }
      this.$refs.userRef.show(obj)
    },
    editUser(row) {
      userDetail({ userId: row.userId }).then(res => {
        const obj = {
          title: '修改用户',
          data: res.data
        }
        this.$refs.userRef.show(obj)
      })
    },
    dels(row) {
      this.$confirm(`本操作将删除该用户，是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            userIds: [row.userId]
          }
          deleteUser(params)
            .then(res => {
              if (res.code === 200) {
                this.paginationSize()
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                })
              }
            })
            .catch(err => {
              this.$message({
                message: err.message,
                type: 'error'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    changeStatus(row) {
      this.$confirm(
        `本操作将${row.enableFlag ? '开启' : '关闭'}该用户，是否继续？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const params = {
            flag: row.enableFlag ? 'y' : 'n',
            userIds: [row.userId]
          }
          enableUser(params).then(res => {
            if (res.code === 200) {
              this.$message.success('更改状态成功')
            }
            this.initUser()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
          this.initUser()
        })
    },
    roleManage() {
      this.$router.push({
        path: 'roleManage'
      })
    },
    addUserBatch() {
      this.addFormVisible = true
    },
    delUserBatch() {
      const userIds = []
      this.multipleSelection.forEach(item => {
        userIds.push(item.userId)
      })
      if (userIds.length < 1) {
        this.$message({
          type: 'info',
          message: '请选择用户'
        })
        return
      }
      this.$confirm(`本操作将删除用户，是否继续？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            userIds: userIds
          }
          deleteUser(params)
            .then(res => {
              if (res.code === 200) {
                this.paginationSize()
              } else {
                this.$message({
                  message: res.message,
                  type: 'error'
                })
              }
              this.$refs.multipleTable.clearSelection()
            })
            .catch(err => {
              this.$message({
                message: err.message,
                type: 'error'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
          this.$refs.multipleTable.clearSelection()
        })
    },
    listShow(row) {
      if (row) {
        this.initUser()
      }
    },
    handleClose(row) {
      this.addFormVisible = row
    }
  }
}
</script>
